package gwu.android;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * Displays an article.  The article selected on the main page is passed here in the Intent.
 * Eventually, find a way to reference the whole database to allow easy transition to 
 * new articles (rather than going back to the main menu)
 * @author Taylor Sandelius
 *
 */
public class ReadArticle extends Activity {
	
    private View mArticleLayout;
    private ScrollView scrollBar;
    private Long mRowId;
    private Button choice1Button, choice2Button, choice3Button, choice4Button;
    private ArrayList<Integer> updatedScores;
    private ArrayList<Integer> wordIds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.read_article);

		mArticleLayout = findViewById(R.id.articleLayout);
		scrollBar = (ScrollView) findViewById(R.id.scrollBox);
		choice1Button = (Button) findViewById(R.id.choice1);
		choice2Button = (Button) findViewById(R.id.choice2);
		choice3Button = (Button) findViewById(R.id.choice3);
		choice4Button = (Button) findViewById(R.id.choice4);
		final Button[] buttons = new Button[4];
		buttons[0] = choice1Button;
		buttons[1] = choice2Button;
		buttons[2] = choice3Button;
		buttons[3] = choice4Button;
        mRowId = null;
        
        // Set buttons to disappear when user scrolls
        scrollBar.setOnTouchListener(new View.OnTouchListener() {		
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				for(Button b : buttons){
					b.setVisibility(View.GONE);
				}
				return false;
			}
		});
        //Retrieve the title, article text, wordIds of the word items, etc. from the Intent
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            setTitle(extras.getString(ArticleDbAdapter.KEY_TITLE));
            String text = extras.getString(ArticleDbAdapter.KEY_BODY);
            wordIds = extras.getIntegerArrayList(WordItemsDbAdapter.KEY_WORDID); //extras.getString(WordItemsDbAdapter.KEY_WORDID);
            updatedScores = extras.getIntegerArrayList(WordItemsDbAdapter.KEY_SCORE);
            final ArrayList<String> answers = extras.getStringArrayList(WordItemsDbAdapter.KEY_ANSWER);
            ArrayList<String> foils1 = extras.getStringArrayList(WordItemsDbAdapter.KEY_FOIL1);
            ArrayList<String> foils2 = extras.getStringArrayList(WordItemsDbAdapter.KEY_FOIL2);
            ArrayList<String> foils3 = extras.getStringArrayList(WordItemsDbAdapter.KEY_FOIL3);
            
            Spanned textFormatted = android.text.Html.fromHtml(text);//This is the formatted text
            mRowId = extras.getLong(ArticleDbAdapter.KEY_ROWID);
            
            String textString = Html.fromHtml(text).toString(); //text without html tags - use for inserting word indices?
            String[] textArray = text.split("\\s*((?<=[,.()])|(?=[.,()]))\\s*|\\s+");  //  HTML usuage/<\\s*(\\w+\\b)<\\s*\\/\\s*\\1\\s*>|\\s+");
            
            final int[] currentArray = new int[wordIds.size()];
            for(int i = 0; i < wordIds.size(); i++){
            	currentArray[i] = i;
            }
            
            Iterator<Integer> words = wordIds.iterator();
            int currentWordIndex = 0;
            int num = 0;
            //Loop through all the wordIds of words that the user will be tested on
            while(words.hasNext()){ 
            	final int wordId = words.next();
            	final int current = currentArray[num];
            	final ArrayList<String> choices = new ArrayList<String>();//array of word choices
            	choices.add(answers.get(current));
            	choices.add(foils1.get(current));
            	choices.add(foils2.get(current));
            	choices.add(foils3.get(current));
            	final String answer = answers.get(current);
            	int predictedWordItemIndex = wordIds.get(current);

            	//Add a section of the text to the array list textBlock and convert to a String
            	ArrayList<String> textBlock = new ArrayList<String>();
            	for(int i = currentWordIndex; i < predictedWordItemIndex; i++){
            		textBlock.add(textArray[i]);
            	}
            	String textBlockString = "";
            	for(int i = 0; i < textBlock.size(); i++){
            		textBlockString = textBlockString.concat(textBlock.get(i) + " ");
            	}
            	
            	//Create a TextView object for each text block section
            	TextView textBox = new TextView(this);
            	textBox.setText(android.text.Html.fromHtml(textBlockString));
            	textBox.setLayoutParams(new LayoutParams(
            			LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            	((LinearLayout) mArticleLayout).addView(textBox);
            	
            	//Create a Button for each word item index 
            	final Button b = new Button(this);
            	b.setText(" ----- ");  
            	b.setLayoutParams(new LayoutParams(
            			LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

            	//Buttons appear only when a user clicks on the button
            	b.setOnClickListener(new View.OnClickListener() {				
            		@Override
            		public void onClick(View v) {
            			Collections.shuffle(choices);
            			for(int i = 0; i < choices.size(); i++){
            				buttons[i].setVisibility(View.VISIBLE);
            				buttons[i].setText(choices.get(i));
            				if(answer.equals(choices.get(i))){ //if the user clicks on the correct answer
            					buttons[i].setOnClickListener(new OnClickListener(){
									@Override
									public void onClick(View v) {
										//Set the current word index in updatedScores to 1
										updatedScores.set(current, 1);
										for(Button b2 : buttons){
											b2.setVisibility(View.GONE);
										}
									}		
            					});
            				}
            				else buttons[i].setOnClickListener(new OnClickListener(){//user clicks the wrong answer
								@Override
								public void onClick(View v) {
									//Set the current word index in updatedScores to -1
									updatedScores.set(current, -1);
									for(Button b : buttons){
										b.setVisibility(View.GONE);
									}
								}	
            				});
            			}
            		}
            	});
            	((LinearLayout) mArticleLayout).addView(b);
            	currentWordIndex = predictedWordItemIndex+1;
            	num++;
            }
            
            //Catch the last section of text  --Find a way to include in the loop above?
            String textBlockString = "";
            for(int i = currentWordIndex; i < textArray.length; i++){
            	textBlockString = textBlockString.concat(textArray[i]+" ");
            }
            TextView textBox = new TextView(this);
            textBox.setText(textBlockString);
            textBox.setId(currentWordIndex);
            textBox.setLayoutParams(new LayoutParams(
          		  LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            ((LinearLayout) mArticleLayout).addView(textBox);
        

        }
	}
	
    /**
     * Send the most recent scores back to the main menu to update the word item table
     * @param v
     */
    public void updateScore(View v){
    	Bundle bundle = new Bundle();
    	bundle.putIntegerArrayList(WordItemsDbAdapter.KEY_SCORE, updatedScores);
    	bundle.putLong(WordItemsDbAdapter.KEY_ARTICLEID, mRowId);
    	bundle.putIntegerArrayList(WordItemsDbAdapter.KEY_WORDID, wordIds);

		Intent mIntent = new Intent();
		mIntent.putExtras(bundle);
		setResult(RESULT_OK, mIntent);
    	finish();
    }
}